import RecordRTC from "recordrtc";
import useOverlay from "./useOverlay";
import { showMsg } from "@/utils/vant";
import useVibrate from "./useVibrate";
import useFetchRecord from "./useFetchRecord";

const useRecordRTC = defineStore("recordRTC", () => {
  const isRecording = ref(false);
  const showRecord = ref(false);
  const style = reactive({
    "--van-overlay-z-index": 1,
    "--van-overlay-background": "rgba(0, 0, 0, 0.7)"
  });
  const recorder = ref<RecordRTC | null>(null);
  const audioBlob = ref<Blob | null>(null);
  const resData = reactive({
    msg: "success",
    data: "123456"
  });
  async function startRecording() {
    try {
      const { start } = useVibrate();
      start();
      isRecording.value = true;
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      recorder.value = new RecordRTC(stream, {
        type: "audio"
      });
      recorder.value.startRecording();
    } catch (error) {
      isRecording.value = false;
      if (error instanceof Error && error.name === "NotFoundError") {
        console.error("未找到音频设备，请检查麦克风是否连接并授予权限。");
        showMsg("未找到音频设备，请检查麦克风是否连接并授予权限。");
      } else {
        console.error("录音启动失败：", error);
        showMsg("录音启动失败，请稍后重试。");
      }
    }
  }
  function stopRecording() {
    isRecording.value = false;
    if (recorder.value) {
      recorder.value.stopRecording(() => {
        audioBlob.value = recorder.value?.getBlob() || null;
        if (audioBlob.value) {
          const src = URL.createObjectURL(audioBlob.value);
          showMsg(src);
          // this.$refs.audio.src = URL.createObjectURL(audioBlob.value);
          const { fetchData } = useFetchRecord();
          fetchData();
        }
      });
    }
  }

  function toggleRecord() {
    showRecord.value = !showRecord.value;
    const { toggleShowRecord } = useOverlay();
    toggleShowRecord(showRecord.value);
  }

  return {
    resData,
    showRecord,
    style,
    toggleRecord,
    isRecording,
    recorder,
    audioBlob,
    startRecording,
    stopRecording
  };
});
export const useRecordRTCRefs = () => {
  const recordRTCStore = useRecordRTC();
  return storeToRefs(recordRTCStore);
};
export default useRecordRTC;
